package com.zys.el.time.mq.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zys.el.time.constants.RedisConstants;
import com.zys.el.time.entity.Thinking;
import com.zys.el.time.mq.dto.MqDTO;
import com.zys.el.time.service.ThinkingService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.ZoneOffset;

@Component
public class ThinkingHandler {

    @Resource
    private ThinkingService thinkingService;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void save(MqDTO mqDTO) {
        Thinking thinking = JSON.parseObject(mqDTO.getData(), Thinking.class);
        // 审核
        boolean b = true;
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 设置审核状态
        if (b) thinking.setStatus(1);
        else thinking.setStatus(3);

        // 入库
        thinkingService.save(thinking);

        // 设置Redis
        // 获取锁
        RLock lock = redissonClient.getLock(RedisConstants.THINKING_LOCK_KEY + thinking.getThinkingId());
        if (lock.tryLock()) {
            String key = RedisConstants.THINKING_KEY + thinking.getThinkingId();
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(thinking));
            lock.unlock();
        }

        // 查询是否存在频道的分页
        String pageThinkingKey = RedisConstants.PAGE_THINKING_KEY + thinking.getChannelId();
        long milli = thinking.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        stringRedisTemplate.opsForZSet().addIfAbsent(pageThinkingKey, String.valueOf(thinking.getThinkingId()), milli);
    }


}
